package com.ruoyi.weixin.controller;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.weixin.domain.WxUser;
import com.ruoyi.weixin.domain.vo.LoginMaDTO;
import com.ruoyi.weixin.domain.vo.MpPhoneNumber;
import com.ruoyi.weixin.domain.vo.WxOpenDataDTO;
import com.ruoyi.weixin.service.WxUserService;
import com.ruoyi.weixin.utils.ThirdSessionHolder;
import com.ruoyi.weixin.utils.WxMaUtil;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/weixin/api/ma/wxuser")
@Api(tags = "小程序用户API")
public class WxUserController {
    private final WxUserService wxUserService;

    @ApiOperation("小程序用户登录")
    @PostMapping("/login")
    public AjaxResult login(HttpServletRequest request, @RequestBody LoginMaDTO loginMaDTO){
        try {
            WxUser wxUser = wxUserService.loginMa(WxMaUtil.getAppId(request),loginMaDTO.getJsCode());
            return AjaxResult.success(wxUser);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("获取手机号")
    @PostMapping("/getPhoneNum")
    public AjaxResult getPhoneNum(HttpServletRequest request, @RequestBody MpPhoneNumber mpPhoneNumber) {
        String phone = wxUserService.getPhoneNum(WxMaUtil.getAppId(request), mpPhoneNumber);
        return AjaxResult.success(phone);
    }

    /**
     * 获取用户信息
     * @param
     * @return
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping
    public AjaxResult get(){
        Long id = ThirdSessionHolder.getThirdSession().getWxUserId();
        return AjaxResult.success(wxUserService.getById(id));
    }

    /**
     * 保存用户信息
     * @param wxOpenDataDTO
     * @return
     */
    @ApiOperation(value = "保存用户信息")
    @PostMapping
    public AjaxResult saveOrUptateWxUser(@RequestBody WxOpenDataDTO wxOpenDataDTO){
        wxOpenDataDTO.setAppId(ThirdSessionHolder.getThirdSession().getAppId());
        wxOpenDataDTO.setUserId(ThirdSessionHolder.getThirdSession().getWxUserId());
        wxOpenDataDTO.setSessionKey(ThirdSessionHolder.getThirdSession().getSessionKey());
        WxUser wxUser = wxUserService.saveOrUptateWxUser(wxOpenDataDTO);
        return AjaxResult.success(wxUser);
    }
}
